import { toLogin, getInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
const user = {
  state: {
    token: getToken(),
    name: ''
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    }
  },
  actions: {
    // 登录
    login: ({
      commit
    }, loginInfo) => {
      const username = loginInfo.username.trim()
      const password = loginInfo.password
      return new Promise((resolve, reject) => {
        toLogin(username, password).then(res => {
          console.log(res)
          setToken(res.token)
          commit('SET_TOKEN', res.token)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 获取用户信息
    GetInfo({ commit, state }){
      return new Promise((resolve, reject) => {
        getInfo(state.token).then(res => {
          const user = res.userName
          commit('SET_NAME', user)
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 退出登录
    LogOut({
      commit
    }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    }
  }
}

export default user